import logging

from flask import g

from info.utils.commons import user_login_data
from info.utils.response_code import RET
from info.models import User, News, Category
from . import index_blue
from info import redis_store
import logging
from flask import current_app, render_template, session, request, jsonify

# 首页新闻列表
# 请求路径/newlist
# 请求方式GET
# 请求参数cid,page,per_page
# 返回值:data

@index_blue.route('/newslist')
def newlist():
    # 1获取参数
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '5')
    # 2参数类型转换,方便分页查询
    try:
        page = int(page)
        per_page =int(per_page)
    except Exception as e:
        page = 1
        per_page = 5


    # 3 分页查询数据,组织数据
    try:
        condition = ''
        if cid != '1':
            condition = (News.category_id == cid)
        paginate = News.query.filter(condition).order_by(News.create_time.desc()).paginate(page, per_page, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg='获取新闻失败')

    totalPage = paginate.pages  #共有多少页
    items = paginate.items  #当前页面的所有对象
    currentPage = paginate.page  #当前页

    #将对象列表转换为字典列表
    newsList = []
    for news in items:
        newsList.append(news.to_dict())

    # 返回响应,携带数据
    return jsonify(errno=RET.OK, errmsg='获取成功', totalPage=totalPage, currentPage=currentPage, newsList=newsList)


@index_blue.route('/', methods=['GET', 'POST'])
@user_login_data
def show_index():
    # 1,测试数据库
    # db.create_all()
    # 2.测试redis存取数据
    # redis_store.set('image_code', 'AABB', 15)
    # redis_store.setex('image_code', 15, 'BBCC')
    # 3.测试session信息
    # session['user_name'] = 'laowang'

    # (方法1)日志信息的使用
    # logging.debug('调试信息')
    # logging.info('详细信息')
    # logging.warning('警告信息')
    # logging.error('错误信息')

    # (方法2)区别在控制台输出的时候有华丽的分割线
    # current_app.logger.error('错误信息')

    # return render_template('news/index.html')
    # 1.获取sesion用户编号
    # user_id = session.get('user_id')
    #
    # # 2.根据用户编号获取对象
    # user = None
    # if user_id:
    #     user = User.query.get(user_id)

    # 按照点击量,查询前是条新闻
    try:
        news_list = News.query.order_by(News.clicks).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
    # 将新闻列表,转为新闻的字典列表
    click_news_list = []
    for news in news_list:
        click_news_list.append(news.to_dict())

    #查询所有的分类,转成字典列表
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    # 携带数据,渲染页面
    dict_data ={
        'user_info':g.user.to_dict() if g.user else '',
        'click_news_list':click_news_list,
        'categories':category_list
    }
    return render_template('news/index.html',data=dict_data)


@index_blue.route('/favicon.ico')
def get_log():
    response = current_app.send_static_file('news/favicon.ico')
    return response